package com.xiaobai.myblog.shiro;

import com.xiaobai.myblog.entity.User;
import com.xiaobai.myblog.service.UserService;
import com.xiaobai.myblog.util.JwtUtils;
import io.jsonwebtoken.Claims;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Component
public class AccountRealm extends AuthorizingRealm {
    @Autowired
    private JwtUtils jwtUtils;
    @Autowired
    private UserService userService;

    @Override
    public boolean supports(AuthenticationToken token) {
        // 判断是否是JwtToken
        return token instanceof JwtToken;
    }

    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        return null;
    }

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        // 上面判断是JwtToken后, 进行强转
        JwtToken jwtToken = (JwtToken) authenticationToken;
        // 获取userId
        String principal = (String)jwtToken.getPrincipal();
        Claims claims = jwtUtils.getClaimByToken(principal);
        String userId = claims.getSubject();
        User user = userService.getById(Long.valueOf(userId));
        if (user == null) {
            throw new UnknownAccountException("账户不存在");
        }
        if (user.getStatus() == -1) {
            throw new LockedAccountException("账户被锁定");
        }
        AccountProfile accountProfile = new AccountProfile();
        BeanUtils.copyProperties(user,  accountProfile);

        // 返回用户信息
        return new SimpleAuthenticationInfo(accountProfile, jwtToken.getCredentials(), getName());
    }
}
